import csv
import sys
import urllib.request
import json
from collections import OrderedDict

instances = {}
platforms = {'mastodon':0, 'pixelfed':0, 'pleroma':0, 'friendica':0, 'error':0, 'unknown':0}

magicHeader={'User-Agent' : "Magic Browser"}

def fallbackDetection(domain):
    try:
        httpRequest = urllib.request.Request(domain, headers=magicHeader) 
        content = urllib.request.urlopen(httpRequest)
        text = content.read().decode('utf-8')

        software=""
        if "https://github.com/tootsuite/mastodon" in text:
            software="mastodon"
        elif "https://github.com/glitch-soc/mastodon" in text:
            software="mastodon"
        elif "<meta property=\"og:site_name\" content=\"pixelfed\">" in text:
            software="pixelfed"
        elif "<title>Pleroma</title>" in text:
            software="pleroma"
        elif "Friendica" in text:
            software="friendica"
        else:
            print("could not find server for " + domain)
            software="unknown"

        platforms[software] += 1
        print(software)

    except Exception:
        print("Error retrieving info of " + domain)
        platforms['error'] += 1

def platformDetection(domain):
    domain = str('https://' + domain)
    apidomain = str(domain + "/.well-known/nodeinfo")
    #print("\nChecking " + domain)

    try:
        apirequest = urllib.request.Request(apidomain, headers=magicHeader)
        content = urllib.request.urlopen(apirequest)
        jsonapi = content.read().decode('utf-8')
        j = json.loads(jsonapi)
        apilink = j["links"][0]["href"]

        apirequest = urllib.request.Request(apilink, headers=magicHeader)
        content = urllib.request.urlopen(apirequest)
        jsonapi = content.read().decode('utf-8')
        j = json.loads(jsonapi)
        software = j["software"]["name"]
        #print(software)

        platforms[software] += 1
        
    except Exception:
        print("API detection failed, using fallback for " + domain)
        fallbackDetection(domain)
        
def addDomain(dom):
    if dom in instances:
        instances[dom] +=1
    else:
        w = {dom:1}
        instances.update(w)

with open(sys.argv[1]) as file:
    csv_reader = csv.reader(file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        line_count += 1
        if line_count > 1:
            addDomain(row[0].split('@')[1])
    print(f'Imported {line_count-1} accounts.')


for instance in sorted(instances, key=instances.get):
    print(instance + ": " + str(instances[instance]))

print("Checking platform type of all instances. This may take a while.")

for instance in instances:
    platformDetection(instance)

for platform in platforms:
    print(platform + ": " + str(platforms[platform]))